<script setup lang="ts">
import { computed, toRaw, watch } from 'vue'
import { onBeforeRouteLeave, useRoute } from 'vue-router'
import type { IpaginationProps, pageChangeProps } from './type'
import router from '@/routes'

const props = defineProps<{ pagination: IpaginationProps }>()

const emits = defineEmits<{
  (e: 'pageChange', data: pageChangeProps): void
}>()

const route = useRoute()

const defaultPagination = {
  pageNo: 1,
  pageSize: 5,
  total: 0,
  pageSizeOptions: ['5', '10', '20', '50'],
  showQuickJumper: true,
  showSizeChanger: true,
  hideOnSinglePage: true,
  addQuery: true,
  size: 'default',
}

const pagination = computed(() => Object.assign({}, defaultPagination, toRaw(props.pagination)))

function pageChange(pageNo: number, pageSize: number) {
  const pageInfo = { pageNo, pageSize }
  pagination.value.addQuery && addQueryToLocation(pageInfo)
  emits('pageChange', pageInfo)
}

// 点击顶部搜索时页码会重置到首页-同步地址栏信息
watch([() => props.pagination?.pageNo, () => props.pagination?.pageSize], (nVal: any[]) => {
  pageChange(nVal[0], nVal[1])
})

function addQueryToLocation(params: any) {
  // 不刷新页面的情况下更新URL中的查询参数
  // const queryString = transformObjToString(params)
  // history.pushState({}, '', `${import.meta.env.VITE_PUBLIC_PATH || ''}${route.path}?${queryString}`)
  // history.pushState({}, '', `${(ENV_CONFIG as any)[import.meta.env.MODE].publicPath || ''}${route.path}?${queryString}`)
  router.push({ path: route.path, query: params })
}

onBeforeRouteLeave((to, from) => {
  // 不是子页面清空query
  const matchedChildPage = to.matched.some((item: any) => from.path === item.path || from.path === item?.redirect)
  if (!matchedChildPage) {
    to.query = from.query = {}
    to.fullPath = to.path
    from.fullPath = from.path
  }
})
</script>

<template>
  <div>
    <a-pagination
      v-model:current="pagination.pageNo"
      v-model:pageSize="pagination.pageSize"
      style="text-align: right; margin: 16px 0"
      :total="pagination.total"
      :show-total="(total: number) => `Total ${total} items`"
      :page-size-options="pagination.pageSizeOptions"
      :show-quick-jumper="pagination.showQuickJumper"
      :show-size-changer="pagination.showSizeChanger"
      :hide-on-single-page="pagination.hideOnSinglePage"
      :size="pagination.size"
      @change="pageChange"
    />
  </div>
</template>
